from django.http import JsonResponse

from users.models import User




def check_token(func):

    def inner(request, *args, **kwargs):
        ret = request.get_signed_cookie("login", default="0", salt="whoami")
        if ret == "success":
            # 已经登录过，继续执行
            return func(request, *args, **kwargs)
        else:
            # 返回错误
            return JsonResponse({})
    return inner


class MyBackend:
    # 校验手机号和密码是否正确
    def authenticate(self, request, username=None, password=None):
        # Check the username/password and return a user
        # 1.根据提供的用户名，通过手机号查找用户
        try:
            user = User.objects.get(mobile=username)
        except Exception as e:
            user = None

        # 2.校验用户密码
        if user and user.check_password(password):
            return user
        else:
            return None


class MyBackend1:
    # 校验邮箱和密码是否正确
    def authenticate(self, request, username=None, password=None):
        # Check the username/password and return a user
        # 1.根据提供的用户名，通过邮箱查找用户
        try:
            user = User.objects.get(email=username)
        except Exception as e:
            user = None

        # 2.校验用户密码
        if user and user.check_password(password):
            return user
        else:
            return None


def jwt_response_payload_handler(token, user=None, request=None, role=None):
    """
    自定义jwt认证成功返回数据
    :token  返回的jwt
    :user   当前登录的用户信息[对象]
    :request 当前本次客户端提交过来的数据
    :role 角色
    """
    if user.first_name:
        name = user.first_name
    else:
        name = user.username
    return {
        # 'code': '0', 'msg': '登录成功',  # 这里用响应码 200 替代这个状态
        'id': user.id,
        'username': user.username,
        'token': token,
        'msg': '登录成功'
    }


from itsdangerous import TimedJSONWebSignatureSerializer as TJWSS
from django.conf import settings


def generate_verify_email_url(user_id):
    # 生成验证邮箱链接
    # 加密一个用户的id, 并返回验证链接
    # http://www.meiduo.site:8000/emails/verification/?token=eyJhbGciOiJIUzUxMiIsImlhdCI6MTU2OTU5MDAyNSwiZXhwIjoxNTY5NTkwMzI1fQ.eyJkYXRhIjoiYnVqaWEifQ.ggn0tKRJKnIZKjQ1WUoASRsJTXyQMhtLyvNsIivrQ6716zytp3sdyYtKDY3nIWXzF9Qt48I233Hl2gfTxfw4-A

    # 生成加密器
    s = TJWSS(secret_key=settings.SECRET_KEY, expires_in=300)

    token = s.dumps({'userid': user_id}).decode()
    # 加密器加密结果是 bytes 类型, 使用前需要 decode
    # eyJhbGciOiJIUzUxMiIsImlhdCI6MTU2OTU5MDAyNSwiZXhwIjoxNTY5NTkwMzI1fQ.eyJkYXRhIjoiYnVqaWEifQ.ggn0tKRJKnIZKjQ1WUoASRsJTXyQMhtLyvNsIivrQ6716zytp3sdyYtKDY3nIWXzF9Qt48I233Hl2gfTxfw4-A

    callback_url = 'http://127.0.0.1:8000/emails/verification/?token='

    verify_email_url = callback_url + token

    return verify_email_url


def decode_email_token(token):
    # 解密token
    # 获取user id,
    # 返回user id

    # 生成加密器
    s = TJWSS(secret_key=settings.SECRET_KEY, expires_in=300)

    try:
        # 解密token
        data = s.loads(token)
    except Exception as e:
        print(e)
        # 解密失败就返回None
        return None

        # 获取userid
    user_id = data.get('userid')

    # 返回userid
    return user_id
